// src/index.js - 重构后的服务器启动文件
import mongoose from "mongoose";
import nodemailer from "nodemailer";
import Tracker from "bittorrent-tracker";
import config from "../../config";
import validateConfig from "./utils/validateConfig";
import createApp from "./app";
import createAdminUser from "./setup/createAdminUser";
import { initScoreUpdater } from "./scheduler/scoringUpdater";

const startServer = async () => {
  // 验证配置
  await validateConfig(config);

  // 初始化邮件服务
  let mail = null;
  if (!process.env.SQ_DISABLE_EMAIL) {
    mail = nodemailer.createTransporter({
      host: process.env.SQ_SMTP_HOST,
      port: process.env.SQ_SMTP_PORT,
      secure: process.env.SQ_SMTP_SECURE,
      auth: {
        user: process.env.SQ_SMTP_USER,
        pass: process.env.SQ_SMTP_PASS,
      },
    });
  }

  // 连接数据库
  const connectToDb = () => {
    console.log("[sq] initiating db connection...");
    mongoose
      .connect(process.env.SQ_MONGO_URL, {
        useNewUrlParser: true,
        useFindAndModify: false,
        useUnifiedTopology: true,
        useCreateIndex: true,
      })
      .catch((e) => {
        console.error(`[sq] error on initial db connection: ${e.message}`);
        setTimeout(connectToDb, 5000);
      });
  };
  connectToDb();

  // 等待数据库连接
  await new Promise((resolve) => {
    mongoose.connection.once("open", async () => {
      console.log("[sq] connected to mongodb successfully");
      await createAdminUser(mail);
      
      // 启动评分更新调度器
      if (process.env.NODE_ENV !== "test") {
        console.log("[sq] 启动评分更新调度器");
        initScoreUpdater();
        
        // 系统启动后，立即更新所有种子评分
        try {
          console.log("[sq] 系统启动，开始更新所有种子评分");
          const { updateAllTorrentScores } = require("./controllers/scoringController");
          await updateAllTorrentScores();
        } catch (error) {
          console.error("[sq] 启动时更新评分失败:", error);
        }
      }
      
      resolve();
    });
  });

  // 初始化 Tracker
  const tracker = new Tracker.Server({
    http: false,
    udp: false,
    ws: false,
  });

  // 创建应用实例
  const app = createApp({ tracker, mail });

  // 启动服务器
  const port = process.env.SQ_PORT || 3001;
  app.listen(port, () => {
    console.log(`[sq] ■ sqtracker running http://localhost:${port}`);
  });

  return app;
};

// 只有在直接运行此文件时才启动服务器
if (require.main === module) {
  startServer().catch(console.error);
}

export default startServer;